import instance from './request';
export function getHousingList() {
  return instance.get('/area/hot');
}
export function getHousingParams() {
  return instance.get('/houses/params');
}
export function getTables(cityId?: string, page: number = 1, pageSize: number = 5, filters?: {
  area?: string;
  subway?: string;
  rentType?: string;
  price?: string;
  more?: string;
  roomType?: string;
  oriented?: string;
  characteristic?: string;
}, start: number = 1, end: number = 2000) {
  // 构建查询参数对象，包含城市ID和分页参数
  const params: any = {};
  console.log('getTables函数调用：cityId=', cityId, 'page=', page, 'pageSize=', pageSize, 'start=', start, 'end=', end);
  if (cityId) {
    params.cityId = cityId;
  }
  // 添加分页参数
  params.page = page;
  params.pageSize = pageSize;
  // 添加开始项和结束项参数
  params.start = start;
  params.end = end;
  
  // 添加筛选条件参数
  if (filters) {
    if (filters.area && filters.area !== '') {
      params.area = filters.area;
    }
    if (filters.subway) {
      params.subway = filters.subway;
    } 
    if (filters.rentType && filters.rentType !== '不限') {
      params.rentType = filters.rentType;
    }
    if (filters.price && filters.price !== '不限') {
      params.price = filters.price;
    }
    if (filters.more) {
      params.more = filters.more;
    }
    if (filters.roomType) {
      params.roomType = filters.roomType;
    }
    if (filters.oriented && filters.oriented !== '') {
      params.oriented = filters.oriented;
    }
    if (filters.characteristic) {
      params.characteristic = filters.characteristic;
    }
  }
  
  return instance.get('/houses', { params });
}
export function getAreaCondition(cityId: string) {
  return instance.get('/houses/condition', { params: { id: cityId } });
}

// 获取房屋详情的API函数
export function getHouseDetail(id: string) {
  return instance.get(`/houses/${id}`);
}

// 添加收藏
export function addFavorite(id: string) {
  const token = localStorage.getItem('token');
  return instance.post(`/user/favorites/${id}`, {}, {
    headers: {
      authorization: token || ''
    }
  });
}

// 取消收藏
export function removeFavorite(id: string) {
  const token = localStorage.getItem('token');
  return instance.delete(`/user/favorites/${id}`, {
    headers: {
      authorization: token || ''
    }
  });
}

// 获取收藏列表
export async function getFavorites() {
  const token = localStorage.getItem('token');
  try {
    const response = await instance.get('/user/favorites', {
      headers: {
        authorization: token || ''
      }
    });
    
    // 检查响应数据结构并提供更详细的日志
    console.log('收藏列表API响应:', JSON.stringify(response, null, 2));
    
    // 处理多种可能的响应数据结构
    let favoritesData = [];
    
    // 检查响应是否成功
    if (response && (response.status === 200 || response.code === 200)) {
      // 尝试从不同的位置获取数据
      if (Array.isArray(response.data)) {
        favoritesData = response.data;
      } else if (response.data && Array.isArray(response.data.data)) {
        favoritesData = response.data.data;
      } else if (response.data && Array.isArray(response.data.body)) {
        favoritesData = response.data.body;
      } else if (response.body && Array.isArray(response.body)) {
        favoritesData = response.body;
      } else {
        // 如果没有找到合适的数据结构，尝试直接使用response.data
        favoritesData = response.data || [];
      }
      
      // 规范化返回格式，确保前端可以统一处理
      return {
        ...response,
        code: response.code || 200,
        body: favoritesData,
        data: favoritesData // 为了兼容可能使用data字段的代码
      };
    } else {
      // 响应不成功，但仍尝试提取数据
      console.warn('收藏列表API返回非成功状态:', response?.status || response?.code);
      return {
        ...response,
        body: [],
        data: []
      };
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    // 抛出错误以便调用者能够处理
    throw error;
  }
}